<template>
  <div class="store-reports">
    <el-card class="header-card">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><DataAnalysis /></el-icon>
            店长数据报表
          </span>
          <div class="header-actions">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
              clearable
            />
            <el-button type="primary" :icon="Refresh" @click="refreshData" :loading="loading">
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-icon sales">
            <el-icon><Wallet /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ formatNumber(statisticsData.totalRevenue) }}</div>
            <div class="stat-label">总收入</div>
            <div class="stat-desc">套餐+购物收入</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon cost">
            <el-icon><Money /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ formatNumber(statisticsData.totalCost) }}</div>
            <div class="stat-label">总成本</div>
            <div class="stat-desc">运营成本</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon profit">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">¥{{ formatNumber(statisticsData.totalProfit) }}</div>
            <div class="stat-label">总利润</div>
            <div class="stat-desc">利润率: {{ formatNumber(statisticsData.profitMargin) }}%</div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-icon orders">
            <el-icon><ShoppingCart /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statisticsData.totalOrders }}</div>
            <div class="stat-label">总订单</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 图表区域 -->
    <div class="charts-container">
      <!-- 收入趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="chart-header">
            <span>收入趋势</span>
            <el-radio-group v-model="revenueTimeType" @change="updateRevenueChart">
              <el-radio-button label="week">近7天</el-radio-button>
              <el-radio-button label="month">近30天</el-radio-button>
              <el-radio-button label="quarter">近3个月</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div ref="revenueChartRef" class="chart"></div>
      </el-card>

      <!-- 商品销量排行 -->
      <el-card class="chart-card">
        <template #header>
          <span>商品销量排行</span>
        </template>
        <div ref="productSalesChartRef" class="chart"></div>
      </el-card>

      <!-- 客户分布 -->
      <el-card class="chart-card">
        <template #header>
          <span>客户购买分布</span>
        </template>
        <div ref="customerChartRef" class="chart"></div>
      </el-card>

      <!-- 销售类型分析 -->
      <el-card class="chart-card">
        <template #header>
          <span>销售类型分析</span>
        </template>
        <div ref="salesTypeChartRef" class="chart"></div>
      </el-card>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>销售详情</span>
          <el-button type="primary" :icon="Download" @click="exportData">导出数据</el-button>
        </div>
      </template>
      
      <el-table :data="salesTableData" v-loading="tableLoading" stripe>
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="revenue" label="收入(套餐+购物)" width="150">
          <template #default="scope">¥{{ formatNumber(scope.row.revenue) }}</template>
        </el-table-column>
        <el-table-column prop="orders" label="订单数" width="100" />
        <el-table-column prop="customers" label="客户数" width="100" />
        <el-table-column prop="avgOrderValue" label="客单价" width="120">
          <template #default="scope">¥{{ formatNumber(scope.row.avgOrderValue) }}</template>
        </el-table-column>
        <el-table-column prop="topProduct" label="热销商品" min-width="150" />
        <el-table-column prop="growth" label="增长率" width="100">
          <template #default="scope">
            <span :class="{'growth-positive': scope.row.growth > 0, 'growth-negative': scope.row.growth < 0}">
              {{ scope.row.growth > 0 ? '+' : '' }}{{ scope.row.growth }}%
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DataAnalysis, 
  Refresh, 
  Wallet, 
  ShoppingCart, 
  Box, 
  User, 
  Download,
  Money,
  TrendCharts
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getStoreReportsData, exportStoreReportsData } from '@/api/reports'

// 响应式数据
const loading = ref(false)
const tableLoading = ref(false)
const dateRange = ref([])
const revenueTimeType = ref('month')

// 统计数据
const statisticsData = reactive({
  totalRevenue: 0,
  totalOrders: 0,
  totalProducts: 0,
  totalCustomers: 0
})

// 图表引用
const revenueChartRef = ref(null)
const productSalesChartRef = ref(null)
const customerChartRef = ref(null)
const salesTypeChartRef = ref(null)

// 图表实例
let revenueChart = null
let productSalesChart = null
let customerChart = null
let salesTypeChart = null

// 表格数据
const salesTableData = ref([])

// 格式化数字
const formatNumber = (num) => {
  if (num === null || num === undefined) return '0'
  return Number(num).toLocaleString()
}

// 初始化收入趋势图
const initRevenueChart = () => {
  if (!revenueChartRef.value) return
  
  revenueChart = echarts.init(revenueChartRef.value)
  
  const option = {
    title: {
      text: '收入趋势',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        return `${params[0].axisValue}<br/>总收入: ¥${formatNumber(params[0].value)}<br/><span style="color: #999; font-size: 12px;">包含套餐+购物收入</span>`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: [],
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: (value) => `¥${formatNumber(value)}`
      }
    },
    series: [{
      name: '收入',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: '#409EFF'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1, color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      }
    }]
  }
  
  revenueChart.setOption(option)
}

// 初始化商品销量图
const initProductSalesChart = () => {
  if (!productSalesChartRef.value) return
  
  productSalesChart = echarts.init(productSalesChartRef.value)
  
  const option = {
    title: {
      text: '商品销量排行',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: []
    },
    series: [{
      name: '销量',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#67C23A'
      }
    }]
  }
  
  productSalesChart.setOption(option)
}

// 初始化客户分布图
const initCustomerChart = () => {
  if (!customerChartRef.value) return
  
  customerChart = echarts.init(customerChartRef.value)
  
  const option = {
    title: {
      text: '客户购买分布',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [{
      name: '购买次数',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }]
  }
  
  customerChart.setOption(option)
}

// 初始化销售类型图
const initSalesTypeChart = () => {
  if (!salesTypeChartRef.value) return
  
  salesTypeChart = echarts.init(salesTypeChartRef.value)
  
  const option = {
    title: {
      text: '销售类型分析',
      left: 'center',
      textStyle: {
        fontSize: 14,
        color: '#666'
      }
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [{
      name: '销售类型',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['50%', '60%'],
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  
  salesTypeChart.setOption(option)
}

// 获取报表数据
const getReportsData = async () => {
  try {
    loading.value = true
    const params = {
      startDate: dateRange.value?.[0] || null,
      endDate: dateRange.value?.[1] || null,
      timeType: revenueTimeType.value
    }
    
    const response = await getStoreReportsData(params)
    if (response.code === 200) {
      const data = response.data
      
      // 更新统计数据
      Object.assign(statisticsData, data.statistics)
      
      // 更新图表数据
      updateCharts(data)
      
      // 更新表格数据
      salesTableData.value = data.salesDetails || []
    } else {
      ElMessage.error(response.message || '获取报表数据失败')
    }
  } catch (error) {
    console.error('获取报表数据失败:', error)
    ElMessage.error('获取报表数据失败')
  } finally {
    loading.value = false
  }
}

// 更新图表数据
const updateCharts = (data) => {
  // 更新收入趋势图
  if (revenueChart && data.revenueData) {
    revenueChart.setOption({
      xAxis: {
        data: data.revenueData.dates || []
      },
      series: [{
        data: data.revenueData.values || []
      }]
    })
  }
  
  // 更新商品销量图
  if (productSalesChart && data.productSalesData) {
    productSalesChart.setOption({
      yAxis: {
        data: data.productSalesData.names || []
      },
      series: [{
        data: data.productSalesData.values || []
      }]
    })
  }
  
  // 更新客户分布图
  if (customerChart && data.customerData) {
    customerChart.setOption({
      series: [{
        data: data.customerData || []
      }]
    })
  }
  
  // 更新销售类型图
  if (salesTypeChart && data.salesTypeData) {
    salesTypeChart.setOption({
      series: [{
        data: data.salesTypeData || []
      }]
    })
  }
}

// 更新收入图表
const updateRevenueChart = () => {
  getReportsData()
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  getReportsData()
}

// 刷新数据
const refreshData = () => {
  getReportsData()
}

// 导出数据
const exportData = async () => {
  try {
    const params = {
      startDate: dateRange.value?.[0] || null,
      endDate: dateRange.value?.[1] || null
    }
    
    await exportStoreReportsData(params)
    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败')
  }
}

// 窗口大小变化时重置图表大小
const handleResize = () => {
  nextTick(() => {
    revenueChart?.resize()
    productSalesChart?.resize()
    customerChart?.resize()
    salesTypeChart?.resize()
  })
}

// 页面挂载
onMounted(() => {
  nextTick(() => {
    initRevenueChart()
    initProductSalesChart()
    initCustomerChart()
    initSalesTypeChart()
    getReportsData()
    
    // 监听窗口大小变化
    window.addEventListener('resize', handleResize)
  })
})

// 页面卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  revenueChart?.dispose()
  productSalesChart?.dispose()
  customerChart?.dispose()
  salesTypeChart?.dispose()
})
</script>

<style scoped>
.store-reports {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 统计卡片样式 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: #fff;
}

.stat-icon.sales {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.orders {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.cost {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
}

.stat-icon.profit {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.stat-desc {
  font-size: 12px;
  color: #999;
}

/* 图表容器 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  min-height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 350px;
}

/* 表格样式 */
.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.growth-positive {
  color: #67C23A;
}

.growth-negative {
  color: #F56C6C;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .charts-container {
    grid-template-columns: 1fr;
  }
  
  .header-actions {
    flex-direction: column;
    align-items: flex-end;
    gap: 8px;
  }
}
</style> 